/**
 * 登录
 */
import { getUserInfo } from '../../../model/service/account/userInfo';
import { getToken } from '../../../util/token';

export default async function login(ctx: Context, next: Next): Promise<void> {
  const { body } = ctx.request;
  const { username, password } = body

  // 查询用户
  const result = await getUserInfo({ username, password });

  // 登录之后返回token
  const token = getToken({ uid: result.uid, username: result.username });
  ctx.res.setHeader('Authorization',token);
  //解决跨域导致前端获取不到token的问题
  ctx.res.setHeader("Access-Control-Expose-Headers","Authorization");

  if (result.length) {
    ctx.api.success(result, 'sucess');
  } else {
    ctx.api.fail(-1, '用户名或者密码错误');
  }

  return next();
}